package com.wzapp.sitposture.eshop.endpoint;

import com.wzapp.sitposture.common.constant.PayConst;
import com.wzapp.sitposture.common.error.CustomizedException;
import com.wzapp.sitposture.eshop.service.OrderPayService;
import com.wzapp.sitposture.eshop.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 功能: 微信支付异步通知Servlet<br/>
 *
 * @author wangzhijun
 *
 */
public class WeixinNotifyServlet extends HttpServlet{

    private static final Logger log = LoggerFactory.getLogger(WeixinNotifyServlet.class);

    private static final long serialVersionUID = -8685285401859800066L;

    private ApplicationContext context;

    private OrderPayService orderPayService;

    private OrderService orderService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.debug("----------WeixinNotifyServlet--->>>>>>>>>>doGet()<<<<<<<<<<<------------");
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        log.debug("----------WeixinNotifyServlet--->>>>>>>>>>doPost()<<<<<<<<<<<------------");
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");

        String inputLine;
        String notityXml = "";
        String out_trade_no = "";
        //微信给返回的东西
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml += inputLine;
            }
            request.getReader().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isEmpty(notityXml)) {
            log.debug("===============notityXml empty=====");
        }else {
            log.debug(notityXml);

            try {
                SortedMap<String, String> map = dom4jXMLParse(notityXml);
                String appid = (String) map.get("appid");//应用ID
                String mch_id = (String) map.get("mch_id");//商户号
                out_trade_no = (String) map.get("out_trade_no");// 获取商户订单号
                String result_code = (String) map.get("result_code");// 业务结果
                String return_code = (String) map.get("return_code");// SUCCESS/FAIL
                String transaction_id = (String) map.get("transaction_id");//微信支付订单号
                String cash_fee = (String) map.get("cash_fee");//现金支付金额
                String time_end = (String) map.get("time_end");//支付完成时间
                String total_fee = (String) map.get("total_fee");// 获取订单金额

                log.debug("=====================appid:" + appid + ",mch_id:" + mch_id + ",out_trade_no:" + out_trade_no
                + ",result_code:" + result_code + ",return_code:" + return_code + ",transaction_id:" + transaction_id);

                // 业务处理
                try {
                    orderPayService.updateOrderPayed(out_trade_no, transaction_id, PayConst.PAY_METHOD_WEIXIN,
                            "SUCCESS".equalsIgnoreCase(return_code));
                } catch (CustomizedException e) {
                    e.printStackTrace();
                }

            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }

        PrintWriter out = response.getWriter();
        log.debug("===============微信支付成功================orderCode={}",out_trade_no);
        out.println("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
    }

    /**
     * 传入微信回调返回的XML信息
     * 以Map形式返回便于取值
     * dom4j解析XML,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值为空
     * @param strXML
     * @return
     * @throws DocumentException
     */
    @SuppressWarnings("rawtypes")
    public static SortedMap<String, String> dom4jXMLParse(String strXML) throws DocumentException {
        SortedMap<String, String> smap = new TreeMap<String, String>();
        Document doc = DocumentHelper.parseText(strXML);
        Element root = doc.getRootElement();
        for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
            Element e = (Element) iterator.next();
            smap.put(e.getName(), e.getText());
        }
        return smap;
    }

    @Override
    public void init() throws ServletException {
        context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        orderPayService = context.getBean(OrderPayService.class);
        orderService = context.getBean(OrderService.class);
    }

}
